package com.varton;

import com.varton.mapper.CompanyMapper;
import com.varton.mapper.IncrementMapper;
import com.varton.po.Company;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
//        checkCache();
//        checkOneToMany();
        checkNPlusOne();
    }

    public static void checkCache(){
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = factoryBuilder.build(in);
            SqlSession session = factory.openSession();
            IncrementMapper mapper = session.getMapper(IncrementMapper.class);
            System.out.println("first query："+mapper.queryById("1"));
            Thread.sleep(5000);
            System.out.println("====================================================");
            System.out.println("second query："+mapper.queryById("1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void checkOneToMany(){
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = factoryBuilder.build(in);
            SqlSession session = factory.openSession();
            CompanyMapper mapper = session.getMapper(CompanyMapper.class);
            System.out.println(mapper.queryCompany(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void checkNPlusOne(){
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = factoryBuilder.build(in);
            SqlSession session = factory.openSession();
            CompanyMapper mapper = session.getMapper(CompanyMapper.class);
            Company company = mapper.queryCompany(1);
            System.out.println(company.getName());
            Thread.sleep(5000);
            System.out.println(company.getDepartmentList().get(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
